package com.kingyun.gpsinspection.purificationservice.services.jsm.innerservice.impl.fileupload;

import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.common.enums.PageContentTypeEnum;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.fileupload.JsmUploadService;
import com.kingyun.gpsinspection.purificationservice.services.hbaseservice.HbaseRepository;
import com.kingyun.gpsinspection.purificationservice.services.hbaseservice.HbaseUtils;
import com.kingyun.gpsinspection.purificationservice.services.hbaseservice.UploadFile;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;

/**
 * Created by Administrator on 2016/12/8.
 */

public class JsmUploadServiceImpl implements JsmUploadService {
    //保存图片的HBASE表名
    public static final String PIC_TABLE = "file";
    //定义找不到图片所显示的图片
    private static final String NO_FOUND = "E:\\workspace\\Job-Standard-Management-web-Src\\jsm-web\\src\\main\\webapp\\static\\img\\personnel-img\\my-head-img.jpg";
    public Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HbaseRepository userRepository;

    @Override
    public String[] uploadImg(HttpServletRequest request, String filename) throws Exception {
        String hbasepath = null;
        if (filename.indexOf(".") > -1) {
            String suffix = filename.substring(filename.indexOf("."));
            // java 生成四位随机数
            // int i=(int)(Math.random()*9000)+1000;
            // int i= new java.util.Random().nextInt(9000)+1000;也可以
            hbasepath = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_SSS_EN) + "_" + (new Random().nextInt(9000) + 1000) + "_file" + suffix;
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
            logger.info("HBase Application Running");
            HbaseUtils hbaseUtils = context.getBean(HbaseUtils.class);
            hbaseUtils.initialize(PIC_TABLE);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = request.getInputStream().read(buffer))) {
                output.write(buffer, 0, n);
            }
            hbaseUtils.addOrg(hbasepath, output.toByteArray());
            return new String[]{hbasepath, filename};
        } else {
            return new String[]{"error", filename};
        }
    }

    @Override
    public String[] uploadImg(HttpServletRequest request, InputStream input) throws Exception {
        String hbasepath = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_SSS_EN) + "_" + (new Random().nextInt(9000) + 1000) + "_file";
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        logger.info("HBase Application Running");
        HbaseUtils hbaseUtils = context.getBean(HbaseUtils.class);
        hbaseUtils.initialize(PIC_TABLE);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = request.getInputStream().read(buffer))) {
            output.write(buffer, 0, n);
        }
        hbaseUtils.addOrg(hbasepath, output.toByteArray());
        return new String[]{hbasepath};
    }


    public void getImg(HttpServletRequest request, HttpServletResponse response, String imageName, String tableName) throws Exception {
        //非空判断
        if (StringUtils.isNotBlank(imageName)) {
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
            HbaseRepository userRepository = context.getBean(HbaseRepository.class);
            logger.info("HBase Application Running");
            // 从HBase获取组织平面图
            userRepository.initialize(tableName);
            UploadFile img = userRepository.get(imageName);
            // java 字节数组转字节流
            InputStream in = new ByteArrayInputStream(img.getPic());
            OutputStream out = null;
            // 从response对象获取输出流
            try {
                out = response.getOutputStream();
                // 将输入流中的数据读取出来，写到输出流中
                for (int b = -1; (b = in.read()) != -1; ) {
                    out.write(b);
                }
            } catch (Exception e) {
                logger.error("输出图片时出错！", e);
            } finally {
                out.close();
                logger.info("-------关闭输出流---------");
                in.close();
                logger.info("-------关闭输入流---------");
            }

        }
    }

    /**
     * 附件插入hbase中
     *
     * @param request
     * @param filename
     * @return
     * @throws Exception
     */
    @Override
    public String[] uploadFile(HttpServletRequest request, String filename) throws Exception {
        String hbasepath = null;
        if (filename.indexOf(".") > -1) {
            String suffix = filename.substring(filename.indexOf("."));
            // java 生成四位随机数
            // int i=(int)(Math.random()*9000)+1000;
            // int i= new java.util.Random().nextInt(9000)+1000;也可以
            hbasepath = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_SSS_EN) + "_" + (new Random().nextInt(9000) + 1000) + "_file" + suffix;
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
            logger.info("HBase Application Running");
            HbaseUtils userUtils = context.getBean(HbaseUtils.class);
            userUtils.initialize("file");
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = request.getInputStream().read(buffer))) {
                output.write(buffer, 0, n);
            }
            userUtils.addOrg(hbasepath, output.toByteArray());
            return new String[]{hbasepath, filename};
        } else {
            return new String[]{"error", filename};
        }
    }

    /**
     * 上传文件或图片
     *
     * @modify by jiangjx on 2017年1月6日 15:57:08 添加注释,删除无用代码
     */
    @Override
    public String[] uploadImgOrFile(HttpServletRequest request, String filename) throws Exception {
        String hbasepath = null;
        if (filename.indexOf(".") > -1) {
            String suffix = filename.substring(filename.indexOf("."));//获取文件后缀名
            hbasepath = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_SSS_EN) + "_" + (new Random().nextInt(9000) + 1000) + "_file" + suffix;//重命名文件,规则"当前时间_随机4位数_file_后缀名"
            /*建立HBase连接*/
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
            logger.info("HBase Application Running");
            HbaseUtils userUtils = context.getBean(HbaseUtils.class);
            userUtils.initialize("file");
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            /*将上传的文件写入输出流*/
            while (-1 != (n = request.getInputStream().read(buffer))) {
                output.write(buffer, 0, n);
            }
            userUtils.addOrg(hbasepath, output.toByteArray());//执行新增操作
            return new String[]{hbasepath, filename};//返回上传后的文件信息
        } else {
            return new String[]{"error", filename};
        }
    }

    /**
     * 上传二进制流
     * @param suffix
     * @param request
     * @param images
     * @return
     * @throws Exception
     */
    public String[] uploadByte(String suffix,HttpServletRequest request,byte[] images) throws Exception{
        String hbasepath = null;
        hbasepath = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_SSS_EN) + "_" + (new Random().nextInt(9000) + 1000) + "_file" + suffix;//重命名文件,规则"当前时间_随机4位数_file_后缀名"
        logger.info("HBase Application Running");
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        HbaseUtils userUtils = context.getBean(HbaseUtils.class);
        userUtils.initialize("file");
       /* ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
            *//*将上传的文件写入输出流*//*
        while (-1 != (n = request.getInputStream().read(buffer))) {
            output.write(buffer, 0, n);
        }
        bis.read(buffer);*/
        userUtils.addOrg(hbasepath, images);//执行新增操作
        return new String[]{hbasepath, ""};//返回上传后的文件信息
    }


    /**
     * 上传文件
     * @param suffix
     * @param images
     * @param context
     * @return
     * @throws Exception
     */
    public String[] uploadByte(String suffix,byte[] images,ApplicationContext context) throws Exception{
        String hbasepath = null;
        hbasepath = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_SSS_EN) + "_" + (new Random().nextInt(9000) + 1000) + "_file" + suffix;//重命名文件,规则"当前时间_随机4位数_file_后缀名"
        logger.info("HBase Application Running");
        HbaseUtils userUtils = context.getBean(HbaseUtils.class);
        userUtils.initialize("file");
       /* ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
            *//*将上传的文件写入输出流*//*
        while (-1 != (n = request.getInputStream().read(buffer))) {
            output.write(buffer, 0, n);
        }
        bis.read(buffer);*/
        userUtils.addOrg(hbasepath, images);//执行新增操作
        return new String[]{hbasepath, ""};//返回上传后的文件信息
    }


    /**
     * 预览文件或图片
     * created by jiangjx
     *
     * @param fileHbasePath
     * @param request
     * @param response
     * @param tableName
     */
    @Override
    public void getImgOrFile(HttpServletRequest request, HttpServletResponse response, String fileHbasePath, String tableName) throws Exception {
        /*非空判断*/
        if (StringUtils.isNotBlank(fileHbasePath)) {
            /*设置返回页面的头文件参数*/
            String suffix = fileHbasePath.substring(fileHbasePath.indexOf("."));//获取后缀名
            //根据后缀名设置返回文件类型
            for (PageContentTypeEnum typeEnum : PageContentTypeEnum.values()) {
                if (typeEnum.getCode().equals(suffix.toLowerCase())) {
                    response.setContentType(typeEnum.getDescription());
                    break;
                }
            }
            response.setHeader("Content-Disposition", "inline;fileName=" + fileHbasePath);//设定为在线打开文档
            /*建立HBase连接*/
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
            HbaseRepository userRepository = context.getBean(HbaseRepository.class);
            logger.info("HBase Application Running");
            userRepository.initialize(tableName);// 从HBase获取组织平面图
            UploadFile file = userRepository.get(fileHbasePath);
            InputStream in = new ByteArrayInputStream(file.getPic());// java 字节数组转字节流
            OutputStream out = response.getOutputStream();// 从response对象获取输出流
            // 将输入流中的数据读取出来，写到输出流中
            for (int i = -1; (i = in.read()) != -1; ) {
                out.write(i);
            }
            /*关闭输入输出流*/
            out.close();
            logger.info("-------关闭输出流---------");
            in.close();
            logger.info("-------关闭输入流---------");
        }
    }

}
